package com.demo.util;

import com.demo.model.Project;
import com.demo.model.Receiver;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class EmailSender {
    private static final Logger logger = LogManager.getLogger(EmailSender.class);

    private static final ArrayList<Message> messageList = new ArrayList<>();
    public static ArrayList<Message> getMessageList() {
        return messageList;
    }

    private static Session session;

    static {
        createSession();
    }

    public static void createSession() {
        logger.debug("初始化：配置session");
        // 从配置文件加载SMTP属性
        Properties props = ConfigLoader.getMailProperties();

        // 获取账户信息
        String username = props.getProperty("mail.smtp.username");
        String password = props.getProperty("mail.smtp.password");

        session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        logger.info("初始化：配置session结束");
    }

    public static boolean isSessionConnected() {
        try {
            Transport transport = session.getTransport();
            transport.connect();
            boolean isConnected = transport.isConnected();
            transport.close();
            return isConnected;
        } catch (MessagingException e) {
            logger.error("Session连接检查失败", e);
            return false;
        }
    }


    public static void sendEmail() throws MessagingException {
        // 发送邮件
        for (Message message : messageList){
            Transport.send(message);
            logger.info("邮件【{}】发送成功", message.getSubject());
        }

    }

    public static void createEmail(Project project, List<Receiver> receivers){
        messageList.clear();
        // 逐一发送邮件
        for (Receiver receiver : receivers) {
            try {
                // 创建新邮件
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(session.getProperty("mail.smtp.username")));

                // 创建消息体部分
                String subject = project.getProject_name()+"-"+receiver.getCompany_name();
                message.setSubject(subject);
                logger.info("subject:{}", subject);

                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver.getEmail()));
                logger.info("to:{}", receiver.getEmail());

                // 多个抄送地址（数组）
                InternetAddress[] internetAddresses = InternetAddress.parse(project.getCcAddresses());
                message.addRecipients(Message.RecipientType.CC, internetAddresses);
                logger.info("cc:{}", project.getCcAddresses());

                // 创建正文内容
                MimeBodyPart messageBodyPart = new MimeBodyPart();

                String content = FreeMarkerUtil.process("zhengxun.ftl",receiver.getCompany_name(),project);
                messageBodyPart.setContent(content, "text/html;charset=UTF-8");
                //logger.info("content:"+content);

                // 创建多部分消息
                Multipart multipart = new MimeMultipart();
                multipart.addBodyPart(messageBodyPart);

                // 添加附件(暂只支持一个附件)
                if (project.getAttachmentPath() != null) {
                    MimeBodyPart attachmentPart = new MimeBodyPart();
                    DataSource source = new FileDataSource(project.getAttachmentFile());
                    attachmentPart.setDataHandler(new DataHandler(source));
                    attachmentPart.setFileName(project.getAttachmentFile().getName());
                    multipart.addBodyPart(attachmentPart);
                }

                // 设置完整消息内容
                message.setContent(multipart);

                messageList.add(message);
            } catch (MessagingException e) {
                logger.error("message创建失败：{}", receiver, e);
            }
        }
    }

}